import 'package:flutter/services.dart';

/// Phone number input formatter that allows international phone number format
/// Supports format like: +2541234567890
class PhoneNumberInputFormatter extends TextInputFormatter {

  static int length = 16;

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    final text = newValue.text;
    
    // Allow empty text
    if (text.isEmpty) {
      return newValue;
    }
    
    // If text doesn't start with +, add it
    if (!text.startsWith('+')) {
      final newText = '+' + text.replaceAll(RegExp(r'[^\d+]'), '');
      return TextEditingValue(
        text: newText,
        selection: TextSelection.collapsed(offset: newText.length),
      );
    }
    
    // Remove any non-digit characters except the leading +
    final digitsOnly = text.replaceAll(RegExp(r'[^\d+]'), '');
    
    // Ensure only one + at the beginning
    final cleanText = digitsOnly.startsWith('+') 
        ? '+' + digitsOnly.substring(1).replaceAll('+', '')
        : '+' + digitsOnly;
    
    // Limit to reasonable phone number length (15 digits after +)
    if (cleanText.length > length) { // + + 15 digits
      return oldValue;
    }
    
    return TextEditingValue(
      text: cleanText,
      selection: TextSelection.collapsed(offset: cleanText.length),
    );
  }
}
